package com.hoow.shakoow

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.webkit.WebView
//import com.facebook.FacebookSdk
//import com.facebook.appevents.AppEventsLogger
import com.hoow.shakoow.base.BaseActivity
//import com.hoow.shakoow.extend.toCombineUrlPath
//import com.hoow.shakoow.network.PathUrl
import com.hoow.shakoow.utils.*
//import com.hoow.shakoow.utils.analytics.util.AdvertIdUtil
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil
//import com.zhi.syc.data.ASBuilder
//import com.zhi.syc.data.ASSycManager
//import com.zhi.syc.point.ASPointBuilder
//import com.zhi.syc.point.ASPointSycManager
import java.util.*


class ProjectApplication : Application() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        @SuppressLint("StaticFieldLeak")
        lateinit var instance: ProjectApplication

//        var GAID: String = ""
//        var IS_LIMIT_AD_TRACKING_ENABLED: Int = 0
//        var FIREBASE_APP_ID = ""
//        var GA4_APP_INSTANCE_ID = ""

        var mFrontActivityCount = 0
//        var mBankAccountType = 0

//        var mHadGetHomePopWindowList: Boolean = false
//        var mHadGetApplyPopWindowList: Boolean = false
//        var mHadGetReviewPopWindowList: Boolean = false
//        var mHadGetLoaningPopWindowList: Boolean = false
//        var mHadGetRepayPopWindowList: Boolean = false
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
        instance = this

        try {
            //适配android 9webview
            initPieWebView()

            //is login
            UserStateUtil.isDidLogin()

            //as sdk
            initASDeviceLib()

            //life cycle
            initLifeCycleCallback()


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun initASDeviceLib() {
//        try {
//            ASBuilder.setMock(false)
//            ASBuilder.setLog(true)
//            ASBuilder.setServerHost(PathUrl.BASE_URL)
//            ASBuilder.setPathApplist(PathUrl.PATH_APPLIST.toCombineUrlPath())
//            ASBuilder.setPathContactResult(PathUrl.PATH_CONTACT_RESULT.toCombineUrlPath())
//            ASBuilder.setPathContact(PathUrl.PATH_CONTACT.toCombineUrlPath())
//            ASBuilder.setPathMessage(PathUrl.PATH_MESSAGE.toCombineUrlPath())
//            ASBuilder.setPathDevice(PathUrl.PATH_DEVICE.toCombineUrlPath())
//            ASBuilder.setPathImage(PathUrl.PATH_IMAGE.toCombineUrlPath())
//            ASBuilder.setPathBattery(PathUrl.PATH_BATTERY.toCombineUrlPath())
//            ASBuilder.setPathHardware(PathUrl.PATH_HARDWARE.toCombineUrlPath())
//            ASBuilder.setPathStore(PathUrl.PATH_STORE.toCombineUrlPath())
//            ASBuilder.setPathMedia(PathUrl.PATH_MEDIA.toCombineUrlPath())
//            ASBuilder.setPathNetwork(PathUrl.PATH_NETWORK.toCombineUrlPath())
//            ASBuilder.setPathLocation(PathUrl.PATH_LOCATION.toCombineUrlPath())
//            ASBuilder.setPathCalendar(PathUrl.PATH_CALENDAR.toCombineUrlPath())
//            ASBuilder.setPathScanFilePath(PathUrl.PATH_WHATSAPP_DIR.toCombineUrlPath())
//            ASBuilder.setPathSettingAccount(PathUrl.PATH_SETTING_ACCOUNT.toCombineUrlPath())
//            ASBuilder.setPathAduid(PathUrl.PATH_ADUID.toCombineUrlPath())
//            ASBuilder.setAppid(ProjectConfig.Product)
//            ASBuilder.setKeyProduct(ProjectConfig.Product)
//            ASSycManager.getInstance().init(this)
//
//            ASPointBuilder.URL_SERVER_HOST = PathUrl.BASE_URL
//            ASPointBuilder.PATH_POINT_RECORD =
//                PathUrl.PATH_POINT_RECORD.toCombineUrlPath()
//            ASPointBuilder.KEY_PRODUCT = ProjectConfig.Product
//            ASPointBuilder.KEY_APPID = ProjectConfig.Product
//            ASPointBuilder.KEY_VERSION = ProjectConfig.Version.toString()
//            ASPointSycManager.getInstance().init(this)
//
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
    }

    private fun initLifeCycleCallback() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
                println("onActivityStarted:${p0::class.java.simpleName}")
                mFrontActivityCount += 1;
            }

            override fun onActivityResumed(p0: Activity) {
            }

            override fun onActivityPaused(p0: Activity) {
            }

            override fun onActivityStopped(p0: Activity) {
                println("onActivityStopped:${p0::class.java.simpleName}")
                mFrontActivityCount -= 1;
                if (mFrontActivityCount == 0) {
                    println("正在切换到后台，当前activity:${p0::class.java.simpleName}")
                    try {
                        if (p0 is BaseActivity) {
                            var gTag = p0.ACTIVITY_TAG
                            if (gTag.isNotBlank()) {
                                gTag = "BACKGROUND_$gTag"
                                AnalyticsUtil.saveHitPointInfo(
                                    type = gTag,
                                    remark = System.currentTimeMillis().toString()
                                )
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }

    private fun initFacebookLib() {
//        try {
//            FacebookSdk.sdkInitialize(applicationContext)
//            AppEventsLogger.activateApp(this)
//        } catch (e: java.lang.Exception) {
//            e.printStackTrace()
//        }
    }

    //适配android 9网络进程
    private fun initPieWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName(this)
            if (ProjectConfig.Pck != processName) {
                WebView.setDataDirectorySuffix(processName!!)
            }
        }
    }

    private fun getProcessName(context: Context?): String? {
        if (context == null) return null
        val manager: ActivityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == Process.myPid()) {
                return processInfo.processName
            }
        }
        return getString(R.string.app_name).uppercase(Locale.getDefault())
    }
}